import queryString from "query-string";
interface RequestConfig {
  url: string;
  baseUrl: string;
  method?: "GET" | "POST" | "PATCH" | "DELETE" | "PUT";
  query?: {
    [k in string]: any;
  };
  body?: any;
  headers?: HeadersInit;
}
export const request = ({
  baseUrl,
  url,
  method = "GET",
  query = {},
  body = {},
  headers = {
    "Content-Type": "application/json",
  },
}: RequestConfig) => {
  const base = baseUrl + url;
  const appendString = queryString.stringify(query || {});
  const init =
    method !== "GET"
      ? { body: JSON.stringify(body), headers, method }
      : { headers, method };
  return fetch(base + "?" + appendString, init)
    .then((res) => {
      /**
       * 对返回结果进行处理
       */
      if (res.ok) {
        const contentType = res.headers.get("content-type") || "";

        if (contentType.includes("application/json")) {
          return res.json();
        } else if (contentType.includes("text/html")) {
          return res.text();
        }
      } else {
        return Promise.reject(res);
      }
    })
    .catch((reason) => {
      throw new Error(reason);
    });
};
